Jupyter notebook交互输入方法(ipywidgets控件),包括文本框text input box,按钮button等

您所在的位置:网站首页 python input 换行等待输入 Jupyter notebook交互输入方法(ipywidgets控件),包括文本框text input box,按钮button等

Jupyter notebook交互输入方法(ipywidgets控件),包括文本框text input box,按钮button等

2024-07-12 07:57| 来源: 网络整理| 查看: 265

交互式输入用到的包是ipywidgets,如果还未安装,可以在终端中使用pip install ipywidgets安装。

如果安装后无法正常显示控件,请在终端运行jupyter nbextension enable --py widgetsnbextension --sys-prefix。 如果你是jupyter lab用户,请运行jupyter labextension install @jupyter-widgets/jupyterlab-manager并重启Jupyter lab,同时确保Jupyter lab侧边栏的Extension Manager是启用状态。

引用:

import ipywidgets as widgets # 控件库 from IPython.display import display # 显示控件的方法

官方文档:https://ipywidgets.readthedocs.io/en/stable/index.html Github项目地址:https://github.com/jupyter-widgets/ipywidgets

widgets中的控件包括两部分:

UI/HTML element,这是显示在output cell中的部分,通常是实例化后将其作为display函数的实参传递 event handler,控件的注册事件,通常做法是将一个定义好的python函数作为实参传递到控件的事件中 例子 - TextBox import ipywidgets as widgets # 控件库 from IPython.display import display # 显示控件的方法 text = widgets.Text() display(text) def print_value(sender): print(sender.value) text.on_submit(print_value) # 回车以提交内容

text sample 在jupyter notebook中输入以上代码,运行后会在输出区显示一个文本框,在文本框中输入内容并回车后,会触发on_submit事件,并输出文本框中的内容。 再次输入并回车,不会清除上一次的输出,而是换行重新输出(图中未展示)。

常用控件

widgets.Text():文本框,构造函数没有形参,常用事件.on_submit(callback),使用示例见上文

widgets.Button(**kwages):按钮,构造函数的形参包括:

description:显示在按钮上的文字 tooltip:鼠标悬浮时显示的提示文字 icon:图标(没有成功使用过) disabled:bool值,是否禁止交互

常用事件:.on_click(callback)。例子:

btn = widgets.Button(description = "OK", tooltip = 'this is a button') def btn_click(sender): print('Button %s clicked!' % sender.description) btn.on_click(btn_click) display(btn)

button sample

widgets.Box():容器,将其它控件组合在一起的控件,类似.Net中的Panel,在构造时传入一个其它控件的数组,没有常用事件。除此外还有HBox()、VBox()等容器。box = widgets.Box([text,btn]) display(box) 在这里插入图片描述

如果觉得使用Box比较麻烦,可以直接在display()里传入多个控件,也能达到组合效果,但是布局就比较随机了。比如上面的例子也可以直接使用 display(text,btn)。 combine sample

widgets.Label(value:str):普通文本标签,通常与其它控件共同组合在Box中以显示说明文本,在构造时传入实参value作为要显示的文本,没有常用事件。widgets.HBox([widgets.Label(value="The $m$ in $E=mc^2$:"


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3